package com.haha.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haha.community.dao.LoginTicketMapper;
import com.haha.community.entity.LoginTicket;
import com.haha.community.entity.User;
import com.haha.community.dao.UserMapper;
import com.haha.community.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.community.util.CommunityConstant;
import com.haha.community.util.CommunityUtil;
import com.haha.community.util.HostHolder;
import com.haha.community.util.MailUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Yang
 * @since 2020-10-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, CommunityConstant {
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private HostHolder hostHolder;
    @Value("${community.path.domain}")
    private String domain;
    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    @Override
    public Map<String, Object> register(User user) {

        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }

        // 验证账号
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        User u = baseMapper.selectOne(queryWrapper);
        if (u != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        // 验证邮箱
        queryWrapper.clear();
        queryWrapper.eq("email", user.getEmail());
        u = baseMapper.selectOne(queryWrapper);
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));
        //普通用户,默认状态为未激活
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        //设置随机头像
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        baseMapper.insert(user);
        //发邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        // http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailUtil.sendMail(user.getEmail(), "激活账号", content);
        return map;

    }

    @Override
    public int activation(int userId, String code) {
        User user = baseMapper.selectById(userId);
        if (user==null){
            return ACTIVATION_FAILURE;
        }
        if (user.getStatus()==1){
            return ACTIVATION_REPEAT;
        }
        if (user.getStatus()==0&&StringUtils.equals(user.getActivationCode(),code)){
            user.setStatus(1);
            baseMapper.updateById(user);
            return ACTIVATION_SUCCESS;
        }
        return ACTIVATION_FAILURE;
    }

    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {

        HashMap<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(username)){
            map.put("usernameMsg","用户名不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
            return map;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = baseMapper.selectOne(queryWrapper);
        if (user==null){
            map.put("usernameMsg","用户名不存在");
            return map;
        }
        if (user.getStatus()==0){
            map.put("usernameMsg","该账号没有激活，请登录邮箱进行激活");
            return map;
        }
        String newPassword = password+user.getSalt();
        if (!StringUtils.equals(user.getPassword(),CommunityUtil.md5(newPassword))){
            map.put("passwordMsg","密码错误");
            return map;
        }
        //保存ticket
        String ticket = CommunityUtil.generateUUID();
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setTicket(ticket);
        loginTicket.setStatus(0);
        loginTicket.setUserId(user.getId());
        loginTicket.setExpired(new Date(System.currentTimeMillis()+expiredSeconds*1000));
        loginTicketMapper.insert(loginTicket);
        map.put("ticket",ticket);
        return map;
    }

    @Override
    public void logout(String ticket) {
        QueryWrapper<LoginTicket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ticket",ticket);
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setStatus(1);
        loginTicketMapper.update(loginTicket,queryWrapper);
    }

    @Override
    public User findUserByName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        return baseMapper.selectOne(queryWrapper);
    }
}
